namespace DotNetNuke.Entities.Portals
{
    using DotNetNuke.Common;
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Data;
    using DotNetNuke.Entities.Modules;
    using DotNetNuke.Entities.Modules.Definitions;
    using DotNetNuke.Entities.Tabs;
    using DotNetNuke.Entities.Users;
    using DotNetNuke.Framework;
    using DotNetNuke.Security.Permissions;
    using DotNetNuke.Security.Roles;
    using DotNetNuke.Services.FileSystem;
    using DotNetNuke.UI.Skins;
    using ICSharpCode.SharpZipLib.Zip;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections;
    using System.Data;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Web;
    using System.Xml;

    public class PortalController
    {
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Creates a new portal alias
        /// </summary>
        /// <param name="PortalId">Id of the portal</param>
        /// <param name="PortalAlias">Portal Alias to be created</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]    01/11/2005  created
        /// </history>
        /// -----------------------------------------------------------------------------
        public void AddPortalAlias(int PortalId, string PortalAlias)
        {
            PortalAliasController objPortalAliasController = new PortalAliasController();
            if (objPortalAliasController.GetPortalAlias(PortalAlias, PortalId) == null)
            {
                PortalAliasInfo objPortalAliasInfo = new PortalAliasInfo();
                objPortalAliasInfo.PortalID = PortalId;
                objPortalAliasInfo.HTTPAlias = PortalAlias;
                objPortalAliasController.AddPortalAlias(objPortalAliasInfo);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Creates a new portal based on the portal template provided.
        /// </summary>
        /// <param name="PortalName">Name of the portal to be created</param>
        /// <param name="FirstName">Portal Administrator's first name</param>
        /// <param name="LastName">Portal Administrator's last name</param>
        /// <param name="Username">Portal Administrator's username</param>
        /// <param name="Password">Portal Administrator's password</param>
        /// <param name="Email">Portal Administrator's email</param>
        /// <returns>PortalId of the new portal if there are no errors, -1 otherwise.</returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [VMasanas]	03/09/2004	Modified to support new template format.
        /// Portal template file should be processed before admin.template
        /// [cnurse]    01/11/2005  Template parsing moved to CreatePortal
        /// </history>
        /// -----------------------------------------------------------------------------
        private int AddPortalInfo(string PortalName, string FirstName, string LastName, string Username, string Password, string Email, string HomeDirectory)
        {
            int PortalId = -1;
            try
            {
                DateTime datExpiryDate;
                if (Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["DemoPeriod"])) != "")
                {
                    datExpiryDate = Convert.ToDateTime(DotNetNuke.Common.Globals.GetMediumDate(DateAndTime.DateAdd(DateInterval.Day, (double) int.Parse(Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["DemoPeriod"]))), DateAndTime.Now).ToString()));
                }
                else
                {
                    datExpiryDate = Null.NullDate;
                }
                double dblHostFee = 0.0;
                if (Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["HostFee"])) != "")
                {
                    dblHostFee = Convert.ToDouble(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["HostFee"]));
                }
                double dblHostSpace = 0.0;
                if (Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["HostSpace"])) != "")
                {
                    dblHostSpace = Convert.ToDouble(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["HostSpace"]));
                }
                int intSiteLogHistory = -1;
                if (Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["SiteLogHistory"])) != "")
                {
                    intSiteLogHistory = Convert.ToInt32(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["SiteLogHistory"]));
                }
                string strCurrency = Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["HostCurrency"]));
                if (strCurrency == "")
                {
                    strCurrency = "USD";
                }
                PortalId = DataProvider.Instance().AddPortalInfo(PortalName, strCurrency, FirstName, LastName, Username, Password, Email, datExpiryDate, dblHostFee, dblHostSpace, intSiteLogHistory, HomeDirectory);
            }
            catch (Exception exception1)
            {
                
                
            }
            return PortalId;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Creates a new portal.
        /// </summary>
        /// <param name="PortalName">Name of the portal to be created</param>
        /// <param name="FirstName">Portal Administrator's first name</param>
        /// <param name="LastName">Portal Administrator's last name</param>
        /// <param name="Username">Portal Administrator's username</param>
        /// <param name="Password">Portal Administrator's password</param>
        /// <param name="Email">Portal Administrator's email</param>
        /// <param name="Description">Description for the new portal</param>
        /// <param name="KeyWords">KeyWords for the new portal</param>
        /// <param name="TemplatePath">Path where the templates are stored</param>
        /// <param name="TemplateFile">Template file</param>
        /// <param name="PortalAlias">Portal Alias String</param>
        /// <param name="ServerPath">The Path to the root of the Application</param>
        /// <param name="ChildPath">The Path to the Child Portal Folder</param>
        /// <param name="IsChildPortal">True if this is a child portal</param>
        /// <returns>PortalId of the new portal if there are no errors, -1 otherwise.</returns>
        /// <remarks>
        /// After the selected portal template is parsed the admin template ("admin.template") will be
        /// also processed. The admin template should only contain the "Admin" menu since it's the same
        /// on all portals. The selected portal template can contain a <settings /> node to specify portal
        /// properties and a <roles /> node to define the roles that will be created on the portal by default.
        /// </remarks>
        /// <history>
        /// [cnurse]	11/08/2004	created (most of this code was moved from SignUp.ascx.vb)
        /// </history>
        /// -----------------------------------------------------------------------------
        public int CreatePortal(string PortalName, string FirstName, string LastName, string Username, string Password, string Email, string Description, string KeyWords, string TemplatePath, string TemplateFile, string HomeDirectory, string PortalAlias, string ServerPath, string ChildPath, bool IsChildPortal)
        {
            int intPortalId = this.AddPortalInfo(PortalName, FirstName, LastName, Username, Password, Email, HomeDirectory);
            if (HomeDirectory == "")
            {
                HomeDirectory = "Portals/" + intPortalId.ToString();
            }
            string MappedHomeDirectory = new FolderController().GetMappedDirectory(DotNetNuke.Common.Globals.ApplicationPath + "/" + HomeDirectory + "/");
            if (intPortalId == -1)
            {
                return intPortalId;
            }
            int AdministratorId = -1;
            UserController objUser = new UserController();
            UserInfo objAdminUser = new UserInfo();
            try
            {
                objAdminUser.Profile.FirstName = FirstName;
                objAdminUser.Profile.LastName = LastName;
                objAdminUser.PortalID = intPortalId;
                objAdminUser.Membership.Username = Username;
                objAdminUser.Membership.Password = Password;
                objAdminUser.Membership.Email = Email;
                objAdminUser.Membership.Approved = true;
                AdministratorId = objUser.AddUser(objAdminUser);
            }
            catch (Exception exception1)
            {
                
                
            }
            if (AdministratorId > 0)
            {
                if (Directory.Exists(MappedHomeDirectory))
                {
                    DotNetNuke.Common.Globals.DeleteFolderRecursive(MappedHomeDirectory);
                }
                if (IsChildPortal)
                {
                    if (!Directory.Exists(ChildPath))
                    {
                        Directory.CreateDirectory(ChildPath);
                    }
                    if (!File.Exists(ChildPath + @"\Default.aspx"))
                    {
                        File.Copy(DotNetNuke.Common.Globals.HostMapPath + "subhost.aspx", ChildPath + @"\Default.aspx");
                    }
                }
                Directory.CreateDirectory(MappedHomeDirectory);
                File.Copy(DotNetNuke.Common.Globals.HostMapPath + "portal.css", MappedHomeDirectory + "portal.css");
                this.ProcessResourceFile(MappedHomeDirectory, TemplatePath + TemplateFile);
                this.ParseTemplate(intPortalId, TemplatePath, TemplateFile, AdministratorId, PortalTemplateModuleAction.Replace, true);
                this.ParseTemplate(intPortalId, TemplatePath, "admin.template", AdministratorId, PortalTemplateModuleAction.Replace, true);
                PortalInfo objportal = this.GetPortal(intPortalId);
                objportal.Description = Description;
                objportal.KeyWords = KeyWords;
                this.UpdatePortalInfo(objportal.PortalID, objportal.PortalName, objportal.LogoFile, objportal.FooterText, objportal.ExpiryDate, objportal.UserRegistration, objportal.BannerAdvertising, objportal.Currency, objportal.AdministratorId, (double) objportal.HostFee, (double) objportal.HostSpace, objportal.PaymentProcessor, objportal.ProcessorUserId, objportal.ProcessorPassword, objportal.Description, objportal.KeyWords, objportal.BackgroundFile, objportal.SiteLogHistory, objportal.SplashTabId, objportal.HomeTabId, objportal.LoginTabId, objportal.UserTabId, objportal.DefaultLanguage, objportal.TimeZoneOffset, objportal.HomeDirectory);
                objAdminUser.Profile.PreferredLocale = objportal.DefaultLanguage;
                objAdminUser.Profile.TimeZone = objportal.TimeZoneOffset;
                objUser.UpdateUser(objAdminUser);
                DataCache.ClearHostCache(true);
                DataCache.RemoveCache("GetRoles");
                this.AddPortalAlias(intPortalId, PortalAlias);
                return intPortalId;
            }
            this.DeletePortalInfo(intPortalId);
            return -1;
        }

        private int CreateRole(int PortalId, string roleName, string description, float serviceFee, int billingPeriod, string billingFrequency, float trialFee, int trialPeriod, string trialFrequency, bool isPublic, bool isAuto)
        {
            RoleInfo objRoleInfo = new RoleInfo();
            RoleController objRoleController = new RoleController();
            objRoleInfo = objRoleController.GetRoleByName(PortalId, roleName);
            if (objRoleInfo == null)
            {
                objRoleInfo = new RoleInfo();
                objRoleInfo.PortalID = PortalId;
                objRoleInfo.RoleName = roleName;
                objRoleInfo.Description = description;
                objRoleInfo.ServiceFee = Conversions.ToSingle(Interaction.IIf(serviceFee < 0f, 0, serviceFee));
                objRoleInfo.BillingPeriod = billingPeriod;
                objRoleInfo.BillingFrequency = billingFrequency;
                objRoleInfo.TrialFee = Conversions.ToSingle(Interaction.IIf(trialFee < 0f, 0, trialFee));
                objRoleInfo.TrialPeriod = trialPeriod;
                objRoleInfo.TrialFrequency = trialFrequency;
                objRoleInfo.IsPublic = isPublic;
                objRoleInfo.AutoAssignment = isAuto;
                return objRoleController.AddRole(objRoleInfo);
            }
            return objRoleInfo.RoleID;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Deletes a portal permanently
        /// </summary>
        /// <param name="PortalId">PortalId of the portal to be deleted</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [VMasanas]	03/09/2004	Created
        /// [VMasanas]	26/10/2004	Remove dependent data (skins, modules)
        /// </history>
        /// -----------------------------------------------------------------------------
        public void DeletePortalInfo(int PortalId)
        {
            IEnumerator refObjectHelperL0=null;
            SkinController.SetSkin(SkinInfo.RootSkin, PortalId, SkinType.Portal, "");
            SkinController.SetSkin(SkinInfo.RootContainer, PortalId, SkinType.Portal, "");
            SkinController.SetSkin(SkinInfo.RootSkin, PortalId, SkinType.Admin, "");
            SkinController.SetSkin(SkinInfo.RootContainer, PortalId, SkinType.Admin, "");
            ModuleController objModules = new ModuleController();
            try
            {
                refObjectHelperL0 = objModules.GetModules(PortalId).GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    ModuleInfo objModule = (ModuleInfo) refObjectHelperL0.Current;
                    objModules.DeleteModule(objModule.ModuleID);
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
            new UserController().DeleteAllUsers(PortalId);
            DataProvider.Instance().DeletePortalInfo(PortalId);
            DataCache.ClearHostCache(true);
        }

        public static PortalSettings GetCurrentPortalSettings()
        {
            return (PortalSettings) HttpContext.Current.Items["PortalSettings"];
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the total size of a folder
        /// </summary>
        /// <param name="dirInfo">The directory to get the size</param>
        /// <returns>Size of the folder</returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [VMasanas]	18/09/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        private long GetFolderSize(DirectoryInfo dirInfo)
        {
            long size = 0L;
            foreach (System.IO.FileInfo file in dirInfo.GetFiles())
            {
                size += file.Length;
            }
            foreach (DirectoryInfo folder in dirInfo.GetDirectories())
            {
                size += this.GetFolderSize(folder);
            }
            return size;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets information of a portal
        /// </summary>
        /// <param name="PortalId">Id of the portal</param>
        /// <returns>PortalInfo object with portal definition</returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public PortalInfo GetPortal(int PortalId)
        {
            return (PortalInfo) CBO.FillObject(DataProvider.Instance().GetPortal(PortalId), typeof(PortalInfo));
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets information from all portals
        /// </summary>
        /// <returns>ArrayList of PortalInfo objects</returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public ArrayList GetPortals()
        {
            return CBO.FillCollection(DataProvider.Instance().GetPortals(), typeof(PortalInfo));
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the space used by a portal
        /// </summary>
        /// <param name="PortalId">Id of the portal</param>
        /// <returns>Space used in bytes</returns>
        /// <remarks>
        /// If PortalId is -1 or not  present (defaults to -1) the host space (\Portals\_default\) will be returned.
        /// </remarks>
        /// <history>
        /// [VMasanas]	27/08/2004	Changed to return the real space used by a portal looking at the files on disc.
        /// </history>
        /// -----------------------------------------------------------------------------
        public int GetPortalSpaceUsed([Optional, DefaultParameterValue(-1)] int PortalId)
        {
            string path;
            if (PortalId == -1)
            {
                path = DotNetNuke.Common.Globals.HostMapPath;
            }
            else
            {
                PortalController objPortalController = new PortalController();
                path = objPortalController.GetPortal(PortalId).HomeDirectoryMapPath;
            }
            DirectoryInfo folder = new DirectoryInfo(path);
            return Convert.ToInt32(this.GetFolderSize(folder));
        }

        private string ImportFile(int PortalId, string url)
        {
            string strUrl = url;
            if (DotNetNuke.Common.Globals.GetURLType(url) == TabType.File)
            {
                int fileId = new FileController().ConvertFilePathToFileId(url, PortalId);
                if (fileId >= 0)
                {
                    strUrl = "FileID=" + fileId.ToString();
                }
            }
            return strUrl;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes all Files from the template
        /// </summary>
        /// <param name="nodeFiles">Template file node for the Files</param>
        /// <param name="PortalId">PortalId of the new portal</param>
        /// <history>
        /// [cnurse]	11/09/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        private void ParseFiles(XmlNodeList nodeFiles, int PortalId, string folderPath)
        {
            IEnumerator refObjectHelperL0=null;
            FileController objController = new FileController();
            try
            {
                refObjectHelperL0 = nodeFiles.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    int FileId;
                    XmlNode node = (XmlNode) refObjectHelperL0.Current;
                    string fileName = XmlUtils.GetNodeValue(node, "filename", "");
                    DotNetNuke.Services.FileSystem.FileInfo objInfo = objController.GetFile(fileName, PortalId, folderPath);
                    if (objInfo == null)
                    {
                        objInfo = new DotNetNuke.Services.FileSystem.FileInfo();
                        objInfo.PortalId = PortalId;
                        objInfo.FileName = fileName;
                        objInfo.Extension = XmlUtils.GetNodeValue(node, "extension", "");
                        objInfo.Size = XmlUtils.GetNodeValueInt(node, "size", 0);
                        objInfo.Width = XmlUtils.GetNodeValueInt(node, "width", 0);
                        objInfo.Height = XmlUtils.GetNodeValueInt(node, "height", 0);
                        objInfo.ContentType = XmlUtils.GetNodeValue(node, "contenttype", "");
                        FileId = objController.AddFile(objInfo, folderPath);
                    }
                    else
                    {
                        FileId = objInfo.FileId;
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Parses folder permissions
        /// </summary>
        /// <param name="nodeFolderPermissions">Node for folder permissions</param>
        /// <param name="PortalID">PortalId of new portal</param>
        /// <param name="FolderId">FolderId of folder being processed</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	11/09/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        private void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, int PortalID, int FolderId, string folderPath)
        {
            IEnumerator refObjectHelperL0=null;
            FolderPermissionCollection objFolderPermissions = new FolderPermissionCollection();
            PermissionController objPermissionController = new PermissionController();
            FolderPermissionController objFolderPermissionController = new FolderPermissionController();
            RoleController objRoleController = new RoleController();
            try
            {
                refObjectHelperL0 = nodeFolderPermissions.GetEnumerator();
                int PermissionID=0;
                while (refObjectHelperL0.MoveNext())
                {
                    XmlNode xmlFolderPermission = (XmlNode) refObjectHelperL0.Current;
                    string PermissionKey = XmlUtils.GetNodeValue(xmlFolderPermission, "permissionkey", "");
                    string PermissionCode = XmlUtils.GetNodeValue(xmlFolderPermission, "permissioncode", "");
                    string RoleName = XmlUtils.GetNodeValue(xmlFolderPermission, "rolename", "");
                    bool AllowAccess = XmlUtils.GetNodeValueBoolean(xmlFolderPermission, "allowaccess", false);
                    ArrayList arrPermissions = objPermissionController.GetPermissionByCodeAndKey(PermissionCode, PermissionKey);
                    int refIntHelperL0 = arrPermissions.Count - 1;
                    for (int i = 0; i <= refIntHelperL0; i++)
                    {
                        PermissionInfo objPermission = (PermissionInfo) arrPermissions[i];
                        PermissionID = objPermission.PermissionID;
                    }
                    int RoleID = -2147483648;
                    string refStringHelperL0 = RoleName;
                    if (refStringHelperL0 == "All Users")
                    {
                        RoleID = Convert.ToInt32("-1");
                    }
                    else if (refStringHelperL0 == "Unauthenticated Users")
                    {
                        RoleID = Convert.ToInt32("-3");
                    }
                    else
                    {
                        RoleInfo objRole = objRoleController.GetRoleByName(PortalID, RoleName);
                        if (objRole != null)
                        {
                            RoleID = objRole.RoleID;
                        }
                    }
                    if ((RoleID != -2147483648) && AllowAccess)
                    {
                        FileSystemUtils.SetFolderPermission(PortalID, FolderId, PermissionID, RoleID, folderPath);
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes all Folders from the template
        /// </summary>
        /// <param name="nodeFolders">Template file node for the Folders</param>
        /// <param name="PortalId">PortalId of the new portal</param>
        /// <history>
        /// [cnurse]	11/09/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        private void ParseFolders(XmlNode nodeFolders, int PortalId)
        {
            IEnumerator refObjectHelperL0=null;
            FolderController objController = new FolderController();
            try
            {
                refObjectHelperL0 = nodeFolders.SelectNodes("//folder").GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    int FolderId;
                    XmlNode node = (XmlNode) refObjectHelperL0.Current;
                    string folderPath = XmlUtils.GetNodeValue(node, "folderpath", "");
                    FolderInfo objInfo = objController.GetFolder(PortalId, folderPath);
                    if (objInfo == null)
                    {
                        FolderId = objController.AddFolder(PortalId, folderPath);
                    }
                    else
                    {
                        FolderId = objInfo.FolderID;
                    }
                    XmlNodeList nodeFolderPermissions = node.SelectNodes("folderpermissions/permission");
                    this.ParseFolderPermissions(nodeFolderPermissions, PortalId, FolderId, folderPath);
                    XmlNodeList nodeFiles = node.SelectNodes("files/file");
                    if (folderPath != "")
                    {
                        folderPath = folderPath + "/";
                    }
                    this.ParseFiles(nodeFiles, PortalId, folderPath);
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        private void ParseModulePermissions(XmlNodeList nodeModulePermissions, int PortalId, int ModuleID)
        {
            IEnumerator refObjectHelperL0=null;
            RoleController objRoleController = new RoleController();
            ModulePermissionCollection objModulePermissions = new ModulePermissionCollection();
            ModulePermissionController objModulePermissionController = new ModulePermissionController();
            PermissionController objPermissionController = new PermissionController();
            ModulePermissionCollection objModulePermissionCollection = new ModulePermissionCollection();
            try
            {
                refObjectHelperL0 = nodeModulePermissions.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    XmlNode node = (XmlNode) refObjectHelperL0.Current;
                    string PermissionKey = XmlUtils.GetNodeValue(node, "permissionkey", "");
                    string PermissionCode = XmlUtils.GetNodeValue(node, "permissioncode", "");
                    string RoleName = XmlUtils.GetNodeValue(node, "rolename", "");
                    bool AllowAccess = XmlUtils.GetNodeValueBoolean(node, "allowaccess", false);
                    int RoleID = -2147483648;
                    string refStringHelperL0 = RoleName;
                    if (refStringHelperL0 == "All Users")
                    {
                        RoleID = Convert.ToInt32("-1");
                    }
                    else if (refStringHelperL0 == "Unauthenticated Users")
                    {
                        RoleID = Convert.ToInt32("-3");
                    }
                    else
                    {
                        RoleInfo objRole = objRoleController.GetRoleByName(PortalId, RoleName);
                        if (objRole != null)
                        {
                            RoleID = objRole.RoleID;
                        }
                    }
                    if (RoleID != -2147483648)
                    {
                        int PermissionID = -1;
                        ArrayList arrPermissions = objPermissionController.GetPermissionByCodeAndKey(PermissionCode, PermissionKey);
                        int refIntHelperL0 = arrPermissions.Count - 1;
                        for (int i = 0; i <= refIntHelperL0; i++)
                        {
                            PermissionInfo objPermission = (PermissionInfo) arrPermissions[i];
                            PermissionID = objPermission.PermissionID;
                        }
                        if (PermissionID != -1)
                        {
                            ModulePermissionInfo objModulePermission = new ModulePermissionInfo();
                            objModulePermission.ModuleID = ModuleID;
                            objModulePermission.PermissionID = PermissionID;
                            objModulePermission.RoleID = RoleID;
                            objModulePermission.AllowAccess = Convert.ToBoolean(XmlUtils.GetNodeValue(node, "allowaccess", ""));
                            objModulePermissionController.AddModulePermission(objModulePermission);
                        }
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes all panes and modules in the template file
        /// </summary>
        /// <param name="nodePanes">Template file node for the panes is current tab</param>
        /// <param name="PortalId">PortalId of the new portal</param>
        /// <param name="TabId">Tab being processed</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [VMasanas]	03/09/2004	Created
        /// [VMasanas]	15/10/2004	Modified for new skin structure
        /// [cnurse]	15/10/2004	Modified to allow for merging template
        /// with existing pages
        /// </history>
        /// -----------------------------------------------------------------------------
        private void ParsePanes(XmlNode nodePanes, int PortalId, int TabId, PortalTemplateModuleAction mergeTabs, Hashtable hModules)
        {
            int iModule;
            ModuleInfo objModule;
            IEnumerator refObjectHelperL0=null;
            ModuleDefinitionController objModuleDefinitions = new ModuleDefinitionController();
            ModuleController objModules = new ModuleController();
            ArrayList arrModules = objModules.GetPortalTabModules(PortalId, TabId);
            PortalInfo objportal = this.GetPortal(PortalId);
            if (mergeTabs == PortalTemplateModuleAction.Replace)
            {
                int refIntHelperL0 = arrModules.Count - 1;
                iModule = 0;
                while (iModule <= refIntHelperL0)
                {
                    objModule = (ModuleInfo) arrModules[iModule];
                    objModules.DeleteTabModule(TabId, objModule.ModuleID);
                    iModule++;
                }
            }
            try
            {
                refObjectHelperL0 = nodePanes.ChildNodes.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    XmlNode nodePane = (XmlNode) refObjectHelperL0.Current;
                    if (nodePane.SelectSingleNode("modules") != null)
                    {
                        IEnumerator refObjectHelperL1=null;
                        try
                        {
                            refObjectHelperL1 = nodePane.SelectSingleNode("modules").GetEnumerator();
                            while (refObjectHelperL1.MoveNext())
                            {
                                XmlNode nodeModule = (XmlNode) refObjectHelperL1.Current;
                                int templateModuleID = XmlUtils.GetNodeValueInt(nodeModule, "moduleID", 0);
                                bool IsInstance = false;
                                if ((templateModuleID > 0) && (hModules[templateModuleID] != null))
                                {
                                    IsInstance = true;
                                }
                                DesktopModuleInfo objDesktopModule = DotNetNuke.Common.Globals.GetDesktopModuleByName(XmlUtils.GetNodeValue(nodeModule, "definition", ""));
                                if (objDesktopModule != null)
                                {
                                    ArrayList arrModuleDefinitions = objModuleDefinitions.GetModuleDefinitions(objDesktopModule.DesktopModuleID);
                                    int refIntHelperL1 = arrModuleDefinitions.Count - 1;
                                    for (int intIndex = 0; intIndex <= refIntHelperL1; intIndex++)
                                    {
                                        ModuleDefinitionInfo objModuleDefinition = (ModuleDefinitionInfo) arrModuleDefinitions[intIndex];
                                        if (objModuleDefinition != null)
                                        {
                                            bool moduleFound = false;
                                            string modTitle = XmlUtils.GetNodeValue(nodeModule, "title", objModuleDefinition.FriendlyName);
                                            if (mergeTabs == PortalTemplateModuleAction.Merge)
                                            {
                                                int refIntHelperL2 = arrModules.Count - 1;
                                                for (iModule = 0; iModule <= refIntHelperL2; iModule++)
                                                {
                                                    objModule = (ModuleInfo) arrModules[iModule];
                                                    if (modTitle == objModule.ModuleTitle)
                                                    {
                                                        moduleFound = true;
                                                        break;
                                                    }
                                                }
                                            }
                                            if (!moduleFound)
                                            {
                                                int intModuleId;
                                                objModule = new ModuleInfo();
                                                objModule.PortalID = PortalId;
                                                objModule.TabID = TabId;
                                                objModule.ModuleOrder = -1;
                                                objModule.ModuleTitle = modTitle;
                                                objModule.PaneName = XmlUtils.GetNodeValue(nodePane, "name", "");
                                                objModule.ModuleDefID = objModuleDefinition.ModuleDefID;
                                                objModule.CacheTime = XmlUtils.GetNodeValueInt(nodeModule, "cachetime", 0);
                                                objModule.Alignment = XmlUtils.GetNodeValue(nodeModule, "alignment", "");
                                                objModule.IconFile = this.ImportFile(PortalId, XmlUtils.GetNodeValue(nodeModule, "iconfile", ""));
                                                objModule.AllTabs = XmlUtils.GetNodeValueBoolean(nodeModule, "alltabs", false);
                                                switch (XmlUtils.GetNodeValue(nodeModule, "visibility", ""))
                                                {
                                                    case "Maximized":
                                                        objModule.Visibility = VisibilityState.Maximized;
                                                        break;

                                                    case "Minimized":
                                                        objModule.Visibility = VisibilityState.Minimized;
                                                        break;

                                                    case "None":
                                                        objModule.Visibility = VisibilityState.None;
                                                        break;
                                                }
                                                objModule.Color = XmlUtils.GetNodeValue(nodeModule, "color", "");
                                                objModule.Border = XmlUtils.GetNodeValue(nodeModule, "border", "");
                                                objModule.Header = XmlUtils.GetNodeValue(nodeModule, "header", "");
                                                objModule.Footer = XmlUtils.GetNodeValue(nodeModule, "footer", "");
                                                objModule.InheritViewPermissions = XmlUtils.GetNodeValueBoolean(nodeModule, "inheritviewpermissions", false);
                                                objModule.ModulePermissions = new ModulePermissionCollection();
                                                objModule.StartDate = XmlUtils.GetNodeValueDate(nodeModule, "startdate", Null.NullDate);
                                                objModule.EndDate = XmlUtils.GetNodeValueDate(nodeModule, "enddate", Null.NullDate);
                                                if (XmlUtils.GetNodeValue(nodeModule, "containersrc", "") != "")
                                                {
                                                    objModule.ContainerSrc = XmlUtils.GetNodeValue(nodeModule, "containersrc", "");
                                                }
                                                objModule.DisplayTitle = XmlUtils.GetNodeValueBoolean(nodeModule, "displaytitle", true);
                                                objModule.DisplayPrint = XmlUtils.GetNodeValueBoolean(nodeModule, "displayprint", true);
                                                objModule.DisplaySyndicate = XmlUtils.GetNodeValueBoolean(nodeModule, "displaysyndicate", false);
                                                if (!IsInstance)
                                                {
                                                    intModuleId = objModules.AddModule(objModule);
                                                    if (templateModuleID > 0)
                                                    {
                                                        hModules.Add(templateModuleID, intModuleId);
                                                    }
                                                }
                                                else
                                                {
                                                    objModule.ModuleID = Convert.ToInt32(RuntimeHelpers.GetObjectValue(hModules[templateModuleID]));
                                                    intModuleId = objModules.AddModule(objModule);
                                                }
                                                if ((XmlUtils.GetNodeValue(nodeModule, "content", "") != "") & !IsInstance)
                                                {
                                                    objModule = objModules.GetModule(intModuleId, TabId);
                                                    string strVersion = nodeModule.SelectSingleNode("content").Attributes["version"].Value;
                                                    string strType = nodeModule.SelectSingleNode("content").Attributes["type"].Value;
                                                    string strcontent = nodeModule.SelectSingleNode("content").InnerXml;
                                                    strcontent = strcontent.Substring(9, strcontent.Length - 12);
                                                    strcontent = HttpContext.Current.Server.HtmlDecode(strcontent);
                                                    if ((objModule.BusinessControllerClass != "") & objModule.IsPortable)
                                                    {
                                                        try
                                                        {
                                                            object objObject = RuntimeHelpers.GetObjectValue(Reflection.CreateObject(objModule.BusinessControllerClass, objModule.BusinessControllerClass));
                                                            if (objObject is IPortable)
                                                            {
                                                                ((IPortable) objObject).ImportModule(objModule.ModuleID, strcontent, strVersion, objportal.AdministratorId);
                                                            }
                                                        }
                                                        catch (Exception exception1)
                                                        {
                                                            
                                                            
                                                        }
                                                    }
                                                }
                                                if (!IsInstance)
                                                {
                                                    XmlNodeList nodeModulePermissions = nodeModule.SelectNodes("modulepermissions/permission");
                                                    this.ParseModulePermissions(nodeModulePermissions, PortalId, intModuleId);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (refObjectHelperL1 is IDisposable)
                            {
                                (refObjectHelperL1 as IDisposable).Dispose();
                            }
                        }
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes the settings node
        /// </summary>
        /// <param name="nodeSettings">Template file node for the settings</param>
        /// <param name="PortalId">PortalId of the new portal</param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [VMasanas]	27/08/2004	Created
        /// [VMasanas]	15/10/2004	Modified for new skin structure
        /// [cnurse]    11/21/2004  Modified to use GetNodeValueDate for ExpiryDate
        /// [VMasanas]  02/21/2005  Modified to not overwrite ExpiryDate if not present
        /// </history>
        /// -----------------------------------------------------------------------------
        private void ParsePortalSettings(XmlNode nodeSettings, int PortalId)
        {
            PortalInfo objPortal = this.GetPortal(PortalId);
            objPortal.LogoFile = this.ImportFile(PortalId, XmlUtils.GetNodeValue(nodeSettings, "logofile", ""));
            objPortal.FooterText = XmlUtils.GetNodeValue(nodeSettings, "footertext", "");
            if (nodeSettings.SelectSingleNode("expirydate") != null)
            {
                objPortal.ExpiryDate = XmlUtils.GetNodeValueDate(nodeSettings, "expirydate", Null.NullDate);
            }
            objPortal.UserRegistration = XmlUtils.GetNodeValueInt(nodeSettings, "userregistration", 0);
            objPortal.BannerAdvertising = XmlUtils.GetNodeValueInt(nodeSettings, "banneradvertising", 0);
            if (XmlUtils.GetNodeValue(nodeSettings, "currency", "") != "")
            {
                objPortal.Currency = XmlUtils.GetNodeValue(nodeSettings, "currency", "");
            }
            if (XmlUtils.GetNodeValue(nodeSettings, "hostfee", "") != "")
            {
                objPortal.HostFee = XmlUtils.GetNodeValueSingle(nodeSettings, "hostfee", 0f);
            }
            if (XmlUtils.GetNodeValue(nodeSettings, "hostspace", "") != "")
            {
                objPortal.HostSpace = XmlUtils.GetNodeValueInt(nodeSettings, "hostspace", 0);
            }
            objPortal.BackgroundFile = XmlUtils.GetNodeValue(nodeSettings, "backgroundfile", "");
            objPortal.PaymentProcessor = XmlUtils.GetNodeValue(nodeSettings, "paymentprocessor", "");
            if (XmlUtils.GetNodeValue(nodeSettings, "siteloghistory", "") != "")
            {
                objPortal.SiteLogHistory = XmlUtils.GetNodeValueInt(nodeSettings, "siteloghistory", 0);
            }
            objPortal.DefaultLanguage = XmlUtils.GetNodeValue(nodeSettings, "defaultlanguage", "en-US");
            objPortal.TimeZoneOffset = XmlUtils.GetNodeValueInt(nodeSettings, "timezoneoffset", -8);
            this.UpdatePortalInfo(objPortal.PortalID, objPortal.PortalName, objPortal.LogoFile, objPortal.FooterText, objPortal.ExpiryDate, objPortal.UserRegistration, objPortal.BannerAdvertising, objPortal.Currency, objPortal.AdministratorId, (double) objPortal.HostFee, (double) objPortal.HostSpace, objPortal.PaymentProcessor, objPortal.ProcessorUserId, objPortal.ProcessorPassword, objPortal.Description, objPortal.KeyWords, objPortal.BackgroundFile, objPortal.SiteLogHistory, objPortal.SplashTabId, objPortal.HomeTabId, objPortal.LoginTabId, objPortal.UserTabId, objPortal.DefaultLanguage, objPortal.TimeZoneOffset, objPortal.HomeDirectory);
            if (XmlUtils.GetNodeValue(nodeSettings, "skinsrc", "") != "")
            {
                SkinController.SetSkin(SkinInfo.RootSkin, PortalId, SkinType.Portal, XmlUtils.GetNodeValue(nodeSettings, "skinsrc", ""));
            }
            if (XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", "") != "")
            {
                SkinController.SetSkin(SkinInfo.RootSkin, PortalId, SkinType.Admin, XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", ""));
            }
            if (XmlUtils.GetNodeValue(nodeSettings, "containersrc", "") != "")
            {
                SkinController.SetSkin(SkinInfo.RootContainer, PortalId, SkinType.Portal, XmlUtils.GetNodeValue(nodeSettings, "containersrc", ""));
            }
            if (XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", "") != "")
            {
                SkinController.SetSkin(SkinInfo.RootContainer, PortalId, SkinType.Admin, XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", ""));
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes a node for a Role and creates a new Role based on the information gathered from the node
        /// </summary>
        /// <param name="nodeRole">Template file node for the role</param>
        /// <param name="portalid">PortalId of the new portal</param>
        /// <returns>RoleId of the created role</returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [VMasanas]	26/08/2004	Created
        /// [cnurse]	15/10/2004	Modified to allow for merging template
        /// with existing pages
        /// [cnurse]    12/07/2004  modified to use new CreateRole method, which takes care of
        /// checking if role exists
        /// </history>
        /// -----------------------------------------------------------------------------
        private int ParseRole(XmlNode nodeRole, int PortalId)
        {
            string RoleName = XmlUtils.GetNodeValue(nodeRole, "rolename", "");
            string Description = XmlUtils.GetNodeValue(nodeRole, "description", "");
            float ServiceFee = XmlUtils.GetNodeValueSingle(nodeRole, "servicefee", 0f);
            int BillingPeriod = XmlUtils.GetNodeValueInt(nodeRole, "billingperiod", 0);
            string BillingFrequency = XmlUtils.GetNodeValue(nodeRole, "billingfrequency", "M");
            float TrialFee = XmlUtils.GetNodeValueSingle(nodeRole, "trialfee", 0f);
            int TrialPeriod = XmlUtils.GetNodeValueInt(nodeRole, "trialperiod", 0);
            string TrialFrequency = XmlUtils.GetNodeValue(nodeRole, "trialfrequency", "N");
            bool IsPublic = XmlUtils.GetNodeValueBoolean(nodeRole, "ispublic", false);
            bool AutoAssignment = XmlUtils.GetNodeValueBoolean(nodeRole, "autoassignment", false);
            return this.CreateRole(PortalId, RoleName, Description, ServiceFee, BillingPeriod, BillingFrequency, TrialFee, TrialPeriod, TrialFrequency, IsPublic, AutoAssignment);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes all Roles from the template
        /// </summary>
        /// <param name="nodeRoles">Template file node for the Roles</param>
        /// <param name="PortalId">PortalId of the new portal</param>
        /// <param name="AdministratorId">New portal's Administrator</param>
        /// <param name="AdministratorRole">Used to return to caller the id of the Administrators Role if found</param>
        /// <param name="RegisteredRole">Used to return to caller the id of the Registered Users Role if found</param>
        /// <param name="SubscriberRole">Used to return to caller the id of the Subscribers Role if found</param>
        /// <remarks>
        /// There must be one role for the Administrators function. Only the first node with this mark will be used as the Administrators Role.
        /// There must be one role for the Registered Users function. Only the first node with this mark will be used as the Registered Users Role.
        /// There must be one role for the Subscribers function. Only the first node with this mark will be used as the Subscribers Role.
        /// If these two minimum roles are not found on the template they will be created with default values.
        /// 
        /// The administrator user will be added to the following roles: Administrators, Registered Users and any role specified with autoassignment=true
        /// </remarks>
        /// <history>
        /// [VMasanas]	26/08/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        private void ParseRoles(XmlNode nodeRoles, int PortalId, int AdministratorId, ref int AdministratorRole, ref int RegisteredRole, ref int SubscriberRole)
        {
            IEnumerator refObjectHelperL0=null;
            bool foundAdminRole = false;
            bool foundRegisteredRole = false;
            bool foundSubscriberRole = false;
            try
            {
                refObjectHelperL0 = nodeRoles.SelectNodes("//role").GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    XmlNode node = (XmlNode) refObjectHelperL0.Current;
                    int RoleId = this.ParseRole(node, PortalId);
                    if (((!foundAdminRole && (XmlUtils.GetNodeValue(node, "roletype", "") == "adminrole")) ? 1 : 0) != 0)
                    {
                        foundAdminRole = true;
                        AdministratorRole = RoleId;
                    }
                    if (((!foundRegisteredRole && (XmlUtils.GetNodeValue(node, "roletype", "") == "registeredrole")) ? 1 : 0) != 0)
                    {
                        foundRegisteredRole = true;
                        RegisteredRole = RoleId;
                    }
                    if (((!foundSubscriberRole && (XmlUtils.GetNodeValue(node, "roletype", "") == "subscriberrole")) ? 1 : 0) != 0)
                    {
                        foundSubscriberRole = true;
                        SubscriberRole = RoleId;
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes a single tab from the template
        /// </summary>
        /// <param name="nodeTab">Template file node for the tabs</param>
        /// <param name="PortalId">PortalId of the new portal</param>
        /// <param name="IsAdminTemplate">True when processing admin template, false when processing portal template</param>
        /// <param name="mergeTabs">Flag to determine whether Module content is merged.</param>
        /// <param name="hModules">Used to control if modules are true modules or instances</param>
        /// <param name="hTabs">Supporting object to build the tab hierarchy</param>
        /// <param name="IsNewPortal">Flag to determine is the template is applied to an existing portal or a new one.</param>
        /// <remarks>
        /// When a special tab is found (HomeTab, UserTab, LoginTab, AdminTab) portal information will be updated.
        /// </remarks>
        /// <history>
        /// [VMasanas]	26/08/2004	Removed code to allow multiple tabs with same name.
        /// [VMasanas]	15/10/2004	Modified for new skin structure
        /// [cnurse]	15/10/2004	Modified to allow for merging template
        /// with existing pages
        /// [cnurse]    11/21/2204  modified to use GetNodeValueDate for Start and End Dates
        /// </history>
        /// -----------------------------------------------------------------------------
        private int ParseTab(XmlNode nodeTab, int PortalId, bool IsAdminTemplate, PortalTemplateModuleAction mergeTabs, ref Hashtable hModules, ref Hashtable hTabs, bool IsNewPortal)
        {
            DotNetNuke.Entities.Tabs.TabInfo objTab = null;
            int ParseTab=0;
            TabController objTabs = new TabController();
            string strName = XmlUtils.GetNodeValue(nodeTab, "name", "");
            bool tabExists = true;
            PortalInfo objportal = this.GetPortal(PortalId);
            if (strName != "")
            {
                int intTabId=0;
                if (!IsNewPortal)
                {
                    string parenttabname = "";
                    if (XmlUtils.GetNodeValue(nodeTab, "parent", "") != "")
                    {
                        parenttabname = XmlUtils.GetNodeValue(nodeTab, "parent", "") + "/";
                    }
                    if (hTabs[parenttabname + strName] != null)
                    {
                        objTab = objTabs.GetTab(Convert.ToInt32(RuntimeHelpers.GetObjectValue(hTabs[parenttabname + strName])));
                    }
                }
                if ((objTab == null) | IsNewPortal)
                {
                    tabExists = false;
                    objTab = new DotNetNuke.Entities.Tabs.TabInfo();
                    intTabId = Null.NullInteger;
                    objTab.TabID = intTabId;
                    objTab.PortalID = PortalId;
                    objTab.TabName = XmlUtils.GetNodeValue(nodeTab, "name", "");
                    objTab.Title = XmlUtils.GetNodeValue(nodeTab, "title", "");
                    objTab.Description = XmlUtils.GetNodeValue(nodeTab, "description", "");
                    objTab.KeyWords = XmlUtils.GetNodeValue(nodeTab, "keywords", "");
                    objTab.IsVisible = XmlUtils.GetNodeValueBoolean(nodeTab, "visible", true);
                    objTab.DisableLink = XmlUtils.GetNodeValueBoolean(nodeTab, "disabled", false);
                    objTab.IconFile = this.ImportFile(PortalId, XmlUtils.GetNodeValue(nodeTab, "iconfile", ""));
                    objTab.Url = XmlUtils.GetNodeValue(nodeTab, "url", "");
                    objTab.StartDate = XmlUtils.GetNodeValueDate(nodeTab, "startdate", Null.NullDate);
                    objTab.EndDate = XmlUtils.GetNodeValueDate(nodeTab, "enddate", Null.NullDate);
                    objTab.RefreshInterval = XmlUtils.GetNodeValueInt(nodeTab, "refreshinterval", Null.NullInteger);
                    objTab.PageHeadText = XmlUtils.GetNodeValue(nodeTab, "pageheadtext", Null.NullString);
                    XmlNodeList nodeTabPermissions = nodeTab.SelectNodes("tabpermissions/permission");
                    objTab.TabPermissions = this.ParseTabPermissions(nodeTabPermissions, objportal, objTab.TabID, IsAdminTemplate);
                    if (XmlUtils.GetNodeValue(nodeTab, "skinsrc", "") != "")
                    {
                        objTab.SkinSrc = XmlUtils.GetNodeValue(nodeTab, "skinsrc", "");
                    }
                    if (XmlUtils.GetNodeValue(nodeTab, "containersrc", "") != "")
                    {
                        objTab.ContainerSrc = XmlUtils.GetNodeValue(nodeTab, "containersrc", "");
                    }
                    objTab.ParentId = Null.NullInteger;
                    string tabName = objTab.TabName;
                    if (XmlUtils.GetNodeValue(nodeTab, "parent", "") != "")
                    {
                        if (hTabs[XmlUtils.GetNodeValue(nodeTab, "parent", "")] != null)
                        {
                            objTab.ParentId = Convert.ToInt32(RuntimeHelpers.GetObjectValue(hTabs[XmlUtils.GetNodeValue(nodeTab, "parent", "")]));
                            tabName = XmlUtils.GetNodeValue(nodeTab, "parent", "") + "/" + objTab.TabName;
                        }
                        else
                        {
                            DotNetNuke.Entities.Tabs.TabInfo objParent = objTabs.GetTabByName(XmlUtils.GetNodeValue(nodeTab, "parent", ""), PortalId);
                            if (objParent != null)
                            {
                                objTab.ParentId = objParent.TabID;
                                tabName = objParent.TabName + "/" + objTab.TabName;
                            }
                            else
                            {
                                objTab.ParentId = Null.NullInteger;
                                tabName = objTab.TabName;
                            }
                        }
                    }
                    intTabId = objTabs.AddTab(objTab);
                    if (hTabs[tabName] == null)
                    {
                        hTabs.Add(tabName, intTabId);
                    }
                }
                if (IsAdminTemplate)
                {
                    if (objTab.TabName == "Admin")
                    {
                        objportal.AdminTabId = intTabId;
                        DataProvider.Instance().UpdatePortalSetup(PortalId, objportal.AdministratorId, objportal.AdministratorRoleId, objportal.RegisteredRoleId, objportal.SplashTabId, objportal.HomeTabId, objportal.LoginTabId, objportal.UserTabId, objportal.AdminTabId);
                    }
                }
                else
                {
                    switch (XmlUtils.GetNodeValue(nodeTab, "tabtype", ""))
                    {
                        case "splashtab":
                            objportal.SplashTabId = intTabId;
                            DataProvider.Instance().UpdatePortalSetup(PortalId, objportal.AdministratorId, objportal.AdministratorRoleId, objportal.RegisteredRoleId, objportal.SplashTabId, objportal.HomeTabId, objportal.LoginTabId, objportal.UserTabId, objportal.AdminTabId);
                            break;

                        case "hometab":
                            objportal.HomeTabId = intTabId;
                            DataProvider.Instance().UpdatePortalSetup(PortalId, objportal.AdministratorId, objportal.AdministratorRoleId, objportal.RegisteredRoleId, objportal.SplashTabId, objportal.HomeTabId, objportal.LoginTabId, objportal.UserTabId, objportal.AdminTabId);
                            break;

                        case "logintab":
                            objportal.LoginTabId = intTabId;
                            DataProvider.Instance().UpdatePortalSetup(PortalId, objportal.AdministratorId, objportal.AdministratorRoleId, objportal.RegisteredRoleId, objportal.SplashTabId, objportal.HomeTabId, objportal.LoginTabId, objportal.UserTabId, objportal.AdminTabId);
                            break;

                        case "usertab":
                            objportal.UserTabId = intTabId;
                            DataProvider.Instance().UpdatePortalSetup(PortalId, objportal.AdministratorId, objportal.AdministratorRoleId, objportal.RegisteredRoleId, objportal.SplashTabId, objportal.HomeTabId, objportal.LoginTabId, objportal.UserTabId, objportal.AdminTabId);
                            break;
                    }
                }
                if (!tabExists && (nodeTab.SelectSingleNode("panes") != null))
                {
                    this.ParsePanes(nodeTab.SelectSingleNode("panes"), PortalId, intTabId, mergeTabs, hModules);
                }
            }
            return ParseTab;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Parses tab permissions
        /// </summary>
        /// <param name="nodeTabPermissions">Node for tab permissions</param>
        /// <param name="objPortal">Portal object of new portal</param>
        /// <param name="TabId">TabId of tab being processed</param>
        /// <param name="IsAdminTemplate">Flag to indicate if we are parsing admin template</param>
        /// <returns></returns>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [Vicen鏬	15/10/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        private TabPermissionCollection ParseTabPermissions(XmlNodeList nodeTabPermissions, PortalInfo objPortal, int TabId, bool IsAdminTemplate)
        {
            IEnumerator refObjectHelperL0=null;
            TabPermissionCollection objTabPermissions = new TabPermissionCollection();
            PermissionController objPermissionController = new PermissionController();
            RoleController objRoleController = new RoleController();
            try
            {
                refObjectHelperL0 = nodeTabPermissions.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    int PermissionID=0;
                    XmlNode xmlTabPermission = (XmlNode) refObjectHelperL0.Current;
                    string PermissionKey = XmlUtils.GetNodeValue(xmlTabPermission, "permissionkey", "");
                    string PermissionCode = XmlUtils.GetNodeValue(xmlTabPermission, "permissioncode", "");
                    string RoleName = XmlUtils.GetNodeValue(xmlTabPermission, "rolename", "");
                    bool AllowAccess = XmlUtils.GetNodeValueBoolean(xmlTabPermission, "allowaccess", false);
                    ArrayList arrPermissions = objPermissionController.GetPermissionByCodeAndKey(PermissionCode, PermissionKey);
                    int refIntHelperL0 = arrPermissions.Count - 1;
                    for (int i = 0; i <= refIntHelperL0; i++)
                    {
                        PermissionInfo objPermission = (PermissionInfo) arrPermissions[i];
                        PermissionID = objPermission.PermissionID;
                    }
                    int RoleID = -2147483648;
                    string refStringHelperL0 = RoleName;
                    if (refStringHelperL0 == "All Users")
                    {
                        RoleID = Convert.ToInt32("-1");
                    }
                    else if (refStringHelperL0 == "Unauthenticated Users")
                    {
                        RoleID = Convert.ToInt32("-3");
                    }
                    else
                    {
                        RoleInfo objRole = objRoleController.GetRoleByName(objPortal.PortalID, RoleName);
                        if (objRole != null)
                        {
                            RoleID = objRole.RoleID;
                        }
                        else if (((IsAdminTemplate && (RoleName.ToLower() == "administrators")) ? 1 : 0) != 0)
                        {
                            RoleID = objPortal.AdministratorRoleId;
                        }
                    }
                    if (RoleID != -2147483648)
                    {
                        TabPermissionInfo objTabPermission = new TabPermissionInfo();
                        objTabPermission.TabID = TabId;
                        objTabPermission.PermissionID = PermissionID;
                        objTabPermission.RoleID = RoleID;
                        objTabPermission.AllowAccess = AllowAccess;
                        objTabPermissions.Add(objTabPermission);
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
            return objTabPermissions;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes all tabs from the template
        /// </summary>
        /// <param name="nodeTabs">Template file node for the tabs</param>
        /// <param name="PortalId">PortalId of the new portal</param>
        /// <param name="IsAdminTemplate">True when processing admin template, false when processing portal template</param>
        /// <param name="mergeTabs">Flag to determine whether Module content is merged.</param>
        /// <param name="IsNewPortal">Flag to determine is the template is applied to an existing portal or a new one.</param>
        /// <remarks>
        /// When a special tab is found (HomeTab, UserTab, LoginTab, AdminTab) portal information will be updated.
        /// </remarks>
        /// <history>
        /// [VMasanas]	26/08/2004	Removed code to allow multiple tabs with same name.
        /// [VMasanas]	15/10/2004	Modified for new skin structure
        /// [cnurse]	15/10/2004	Modified to allow for merging template
        /// with existing pages
        /// </history>
        /// -----------------------------------------------------------------------------
        private void ParseTabs(XmlNode nodeTabs, int PortalId, bool IsAdminTemplate, PortalTemplateModuleAction mergeTabs, bool IsNewPortal)
        {
            IEnumerator refObjectHelperL2=null;
            Hashtable hModules = new Hashtable();
            Hashtable hTabs = new Hashtable();
            if (!IsNewPortal)
            {
                IEnumerator refObjectHelperL0=null;
                IEnumerator refObjectHelperL1=null;
                Hashtable hTabNames = new Hashtable();
                try
                {
                    refObjectHelperL0 = GetCurrentPortalSettings().DesktopTabs.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        DotNetNuke.Entities.Tabs.TabInfo objtab = (DotNetNuke.Entities.Tabs.TabInfo) refObjectHelperL0.Current;
                        if (!objtab.IsDeleted & !objtab.IsAdminTab)
                        {
                            string tabname = objtab.TabName;
                            if (!Null.IsNull(objtab.ParentId))
                            {
                                tabname = Conversions.ToString(hTabNames[objtab.ParentId]) + "/" + objtab.TabName;
                            }
                            hTabNames.Add(objtab.TabID, tabname);
                        }
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
                try
                {
                    refObjectHelperL1 = hTabNames.Keys.GetEnumerator();
                    while (refObjectHelperL1.MoveNext())
                    {
                        int i = Conversions.ToInteger(refObjectHelperL1.Current);
                        if (hTabs[RuntimeHelpers.GetObjectValue(hTabNames[i])] != null)
                        {
                            hTabs.Add(RuntimeHelpers.GetObjectValue(hTabNames[i]), i);
                        }
                    }
                }
                finally
                {
                    if (refObjectHelperL1 is IDisposable)
                    {
                        (refObjectHelperL1 as IDisposable).Dispose();
                    }
                }
                hTabNames = null;
            }
            try
            {
                refObjectHelperL2 = nodeTabs.SelectNodes("//tab").GetEnumerator();
                while (refObjectHelperL2.MoveNext())
                {
                    XmlNode nodeTab = (XmlNode) refObjectHelperL2.Current;
                    this.ParseTab(nodeTab, PortalId, IsAdminTemplate, mergeTabs, ref hModules, ref hTabs, IsNewPortal);
                }
            }
            finally
            {
                if (refObjectHelperL2 is IDisposable)
                {
                    (refObjectHelperL2 as IDisposable).Dispose();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processess a template file for the new portal. This method will be called twice: for the portal template and for the admin template
        /// </summary>
        /// <param name="PortalId">PortalId of the new portal</param>
        /// <param name="TemplatePath">Path for the folder where templates are stored</param>
        /// <param name="TemplateFile">Template file to process</param>
        /// <param name="AdministratorId">UserId for the portal administrator. This is used to assign roles to this user</param>
        /// <param name="mergeTabs">Flag to determine whether Module content is merged.</param>
        /// <param name="IsNewPortal">Flag to determine is the template is applied to an existing portal or a new one.</param>
        /// <remarks>
        /// The roles and settings nodes will only be processed on the portal template file.
        /// </remarks>
        /// <history>
        /// [VMasanas]	27/08/2004	Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public void ParseTemplate(int PortalId, string TemplatePath, string TemplateFile, int AdministratorId, PortalTemplateModuleAction mergeTabs, bool IsNewPortal)
        {
            XmlNode node;
            XmlDocument xmlDoc = new XmlDocument();
            int AdministratorRoleId = -1;
            int RegisteredRoleId = -1;
            int SubscriberRoleId = -1;
            RoleController objrole = new RoleController();
            bool isAdminTemplate = TemplateFile == "admin.template";
            try
            {
                xmlDoc.Load(TemplatePath + TemplateFile);
            }
            catch (Exception exception1)
            {
                
                
            }
            if (!isAdminTemplate)
            {
                node = xmlDoc.SelectSingleNode("//portal/settings");
                if ((node != null) & IsNewPortal)
                {
                    this.ParsePortalSettings(node, PortalId);
                }
                node = xmlDoc.SelectSingleNode("//portal/roles");
                if (node != null)
                {
                    this.ParseRoles(node, PortalId, AdministratorId, ref AdministratorRoleId, ref RegisteredRoleId, ref SubscriberRoleId);
                }
                if (AdministratorRoleId == -1)
                {
                    AdministratorRoleId = this.CreateRole(PortalId, "Administrators", "Portal Administrators", 0f, 0, "M", 0f, 0, "N", false, false);
                }
                if (RegisteredRoleId == -1)
                {
                    RegisteredRoleId = this.CreateRole(PortalId, "Registered Users", "Registered Users", 0f, 0, "M", 0f, 0, "N", false, true);
                }
                if (SubscriberRoleId == -1)
                {
                    SubscriberRoleId = this.CreateRole(PortalId, "Subscribers", "A public role for portal subscriptions", 0f, 0, "M", 0f, 0, "N", true, true);
                }
                objrole.AddUserRole(PortalId, AdministratorId, AdministratorRoleId, Null.NullDate);
                objrole.AddUserRole(PortalId, AdministratorId, RegisteredRoleId, Null.NullDate);
                objrole.AddUserRole(PortalId, AdministratorId, SubscriberRoleId, Null.NullDate);
                PortalInfo objportal = this.GetPortal(PortalId);
                DataProvider.Instance().UpdatePortalSetup(PortalId, AdministratorId, AdministratorRoleId, RegisteredRoleId, objportal.SplashTabId, objportal.HomeTabId, objportal.LoginTabId, objportal.UserTabId, objportal.AdminTabId);
                node = xmlDoc.SelectSingleNode("//portal/folders");
                if (node != null)
                {
                    this.ParseFolders(node, PortalId);
                }
                FolderController objController = new FolderController();
                if (objController.GetFolder(PortalId, "") == null)
                {
                    IEnumerator refObjectHelperL0=null;
                    int folderid = objController.AddFolder(PortalId, "");
                    ArrayList arr = new PermissionController().GetPermissionByCodeAndKey("SYSTEM_FOLDER", "");
                    try
                    {
                        refObjectHelperL0 = arr.GetEnumerator();
                        while (refObjectHelperL0.MoveNext())
                        {
                            PermissionInfo objpermission = (PermissionInfo) refObjectHelperL0.Current;
                            FileSystemUtils.SetFolderPermission(PortalId, folderid, objpermission.PermissionID, AdministratorRoleId, "");
                        }
                    }
                    finally
                    {
                        if (refObjectHelperL0 is IDisposable)
                        {
                            (refObjectHelperL0 as IDisposable).Dispose();
                        }
                    }
                }
                if (mergeTabs == PortalTemplateModuleAction.Replace)
                {
                    IEnumerator refObjectHelperL1=null;
                    TabController objTabs = new TabController();
                    ArrayList arrTabs = objTabs.GetTabs(PortalId);
                    try
                    {
                        refObjectHelperL1 = arrTabs.GetEnumerator();
                        while (refObjectHelperL1.MoveNext())
                        {
                            DotNetNuke.Entities.Tabs.TabInfo objTab = (DotNetNuke.Entities.Tabs.TabInfo) refObjectHelperL1.Current;
                            if (!objTab.IsAdminTab)
                            {
                                IEnumerator refObjectHelperL2=null;
                                objTab.TabName = objTab.TabName + "_old";
                                objTab.IsDeleted = true;
                                objTabs.UpdateTab(objTab);
                                ModuleController objModules = new ModuleController();
                                ArrayList arrModules = objModules.GetPortalTabModules(objTab.PortalID, objTab.TabID);
                                try
                                {
                                    refObjectHelperL2 = arrModules.GetEnumerator();
                                    while (refObjectHelperL2.MoveNext())
                                    {
                                        ModuleInfo objModule = (ModuleInfo) refObjectHelperL2.Current;
                                        objModules.DeleteTabModule(objModule.TabID, objModule.ModuleID);
                                    }
                                }
                                finally
                                {
                                    if (refObjectHelperL2 is IDisposable)
                                    {
                                        (refObjectHelperL2 as IDisposable).Dispose();
                                    }
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (refObjectHelperL1 is IDisposable)
                        {
                            (refObjectHelperL1 as IDisposable).Dispose();
                        }
                    }
                }
            }
            node = xmlDoc.SelectSingleNode("//portal/tabs");
            if (node != null)
            {
                this.ParseTabs(node, PortalId, isAdminTemplate, mergeTabs, IsNewPortal);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Processes the resource file for the template file selected
        /// </summary>
        /// <param name="portalPath">New portal's folder</param>
        /// <param name="TemplateFile">Selected template file</param>
        /// <remarks>
        /// The resource file is a zip file with the same name as the selected template file and with
        /// an extension of .resources (to unable this file being downloaded).
        /// For example: for template file "portal.template" a resource file "portal.template.resources" can be defined.
        /// </remarks>
        /// <history>
        /// [VMasanas]	10/09/2004	Created
        /// [cnurse]    11/08/2004  Moved from SignUp to PortalController
        /// [cnurse]    03/04/2005  made Public
        /// [cnurse]    05/20/2005  moved most of processing to new method in FileSystemUtils
        /// </history>
        /// -----------------------------------------------------------------------------
        public void ProcessResourceFile(string portalPath, string TemplateFile)
        {
            try
            {
                ZipInputStream objZipInputStream = new ZipInputStream(new FileStream(TemplateFile + ".resources", FileMode.Open, FileAccess.Read));
                FileSystemUtils.UnzipResources(objZipInputStream, portalPath);
            }
            catch (Exception exception1)
            {
                
                Exception exc = exception1;
                
            }
        }

        public void UpdatePortalExpiry(int PortalId)
        {
            IDataReader dr = DataProvider.Instance().GetPortal(PortalId);
            if (dr.Read())
            {
                DateTime ExpiryDate;
                if (Information.IsDBNull(RuntimeHelpers.GetObjectValue(dr["ExpiryDate"])))
                {
                    ExpiryDate = Convert.ToDateTime(RuntimeHelpers.GetObjectValue(dr["ExpiryDate"]));
                }
                else
                {
                    ExpiryDate = DateAndTime.Now;
                }
                DataProvider.Instance().UpdatePortalInfo(PortalId, Convert.ToString(RuntimeHelpers.GetObjectValue(dr["PortalName"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["LogoFile"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["FooterText"])), DateAndTime.DateAdd(DateInterval.Month, 1.0, ExpiryDate), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["UserRegistration"])), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["BannerAdvertising"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Currency"])), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["AdministratorId"])), Convert.ToDouble(RuntimeHelpers.GetObjectValue(dr["HostFee"])), Convert.ToDouble(RuntimeHelpers.GetObjectValue(dr["HostSpace"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["PaymentProcessor"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["ProcessorUserId"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["ProcessorPassword"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Description"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["KeyWords"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["BackgroundFile"])), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["SiteLogHistory"])), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["SplashTabId"])), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["HomeTabId"])), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["LoginTabId"])), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["UserTabId"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["DefaultLanguage"])), Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["TimeZoneOffset"])), Convert.ToString(RuntimeHelpers.GetObjectValue(dr["HomeDirectory"])));
            }
            dr.Close();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Updates basic portal information
        /// </summary>
        /// <param name="Portal"></param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	10/13/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public void UpdatePortalInfo(PortalInfo Portal)
        {
            this.UpdatePortalInfo(Portal.PortalID, Portal.PortalName, Portal.LogoFile, Portal.FooterText, Portal.ExpiryDate, Portal.UserRegistration, Portal.BannerAdvertising, Portal.Currency, Portal.AdministratorId, (double) Portal.HostFee, (double) Portal.HostSpace, Portal.PaymentProcessor, Portal.ProcessorUserId, Portal.ProcessorPassword, Portal.Description, Portal.KeyWords, Portal.BackgroundFile, Portal.SiteLogHistory, Portal.SplashTabId, Portal.HomeTabId, Portal.LoginTabId, Portal.UserTabId, Portal.DefaultLanguage, Portal.TimeZoneOffset, Portal.HomeDirectory);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Updates basic portal information
        /// </summary>
        /// <param name="PortalId"></param>
        /// <param name="PortalName"></param>
        /// <param name="LogoFile"></param>
        /// <param name="FooterText"></param>
        /// <param name="ExpiryDate"></param>
        /// <param name="UserRegistration"></param>
        /// <param name="BannerAdvertising"></param>
        /// <param name="Currency"></param>
        /// <param name="AdministratorId"></param>
        /// <param name="HostFee"></param>
        /// <param name="HostSpace"></param>
        /// <param name="PaymentProcessor"></param>
        /// <param name="ProcessorUserId"></param>
        /// <param name="ProcessorPassword"></param>
        /// <param name="Description"></param>
        /// <param name="KeyWords"></param>
        /// <param name="BackgroundFile"></param>
        /// <param name="SiteLogHistory"></param>
        /// <param name="HomeTabId"></param>
        /// <param name="LoginTabId"></param>
        /// <param name="UserTabId"></param>
        /// <param name="DefaultLanguage"></param>
        /// <param name="TimeZoneOffset"></param>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public void UpdatePortalInfo(int PortalId, string PortalName, string LogoFile, string FooterText, DateTime ExpiryDate, int UserRegistration, int BannerAdvertising, string Currency, int AdministratorId, double HostFee, double HostSpace, string PaymentProcessor, string ProcessorUserId, string ProcessorPassword, string Description, string KeyWords, string BackgroundFile, int SiteLogHistory, int SplashTabId, int HomeTabId, int LoginTabId, int UserTabId, string DefaultLanguage, int TimeZoneOffset, string HomeDirectory)
        {
            DataProvider.Instance().UpdatePortalInfo(PortalId, PortalName, LogoFile, FooterText, ExpiryDate, UserRegistration, BannerAdvertising, Currency, AdministratorId, HostFee, HostSpace, PaymentProcessor, ProcessorUserId, ProcessorPassword, Description, KeyWords, BackgroundFile, SiteLogHistory, SplashTabId, HomeTabId, LoginTabId, UserTabId, DefaultLanguage, TimeZoneOffset, HomeDirectory);
            DataCache.ClearPortalCache(PortalId, true);
        }
    }
}

